package com.haitaoit.chengquan.utils;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.WindowManager;

import com.haitaoit.chengquan.R;
import com.haitaoit.chengquan.base.BackCall;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.io.ByteArrayOutputStream;

public class GetPhotoOrImage {
    private GetPhotoListener getPhotoListener;
    private String oldfile;
    private Activity context;


    public GetPhotoOrImage(Activity context) {
        this.context = context;

    }

    // 调用图库或者相机获取图片
    public void getImage() {
        Dialog dlg = DialogUtil.ShowPhotoDialog(context, new BackCall() {
            @Override
            public void deal(int which, Object... obj) {
                switch (which) {
                    case R.id.tv_photos:// 图库
                        Intent intent = new Intent();
                        intent.setAction(Intent.ACTION_GET_CONTENT);
                        intent.addCategory(Intent.CATEGORY_OPENABLE);
                        intent.setType("image/*");
                        intent.putExtra("aspectX", 1);
                        intent.putExtra("aspectY", 1);
                        intent.putExtra("outputX", 500);
                        intent.putExtra("outputY", 500);
                        intent.putExtra("crop", "true");
                        intent.putExtra("return-data", true);
                        context.startActivityForResult(intent, 9999);
                        break;
                    case R.id.tv_camera:
                        Intent in = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        context.startActivityForResult(in, 9999);
                        break;
                }
                super.deal(which, obj);
            }
        });
        dlg.setCanceledOnTouchOutside(true);
        dlg.show();

        DisplayMetrics metric = new DisplayMetrics();
        context.getWindowManager().getDefaultDisplay().getMetrics(metric);
        int width = metric.widthPixels; // 屏幕宽度（像素）
        WindowManager.LayoutParams params = dlg.getWindow().getAttributes();
        params.width = width;
        params.gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL;
        dlg.getWindow().setAttributes(params);
    }

    // 记录文件名
    private String filename;
    private Bitmap upbitmap;

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        String file = null;
        switch (requestCode) {
            case 9999:
                if (data != null) {
                    upbitmap = null;
                    if (data.getExtras() != null && !("").equals(data.getExtras())) {
                        upbitmap = (Bitmap) data.getExtras().get("data");
                    } else {
                        String str = data.getDataString();
                        if (str == null) {
                            return;
                        }
                        Uri uri = Uri.parse(str);
                        String path = GetAbserlutePath.getPath(context, uri);
                        if (path.endsWith("png") || path.endsWith("jpg")) {// 图片
                            upbitmap = ImageLoader.getInstance().loadImageSync("file://" + path);
                        } else {
                            ToastUtils.showToast("请选择.jpg或.png格式的图片！");
                            return;
                        }
                    }
                    if (upbitmap == null) {
                        return;
                    }
                    upbitmap = getSmallBitmap(upbitmap);
                    file = bitmapToString(upbitmap);
                    if (file.equals(oldfile)) {// 如果图片未改变或者未选择图片
                        return;
                    }
                    oldfile = file;
                }
                break;
        }
        if (getPhotoListener != null) {
            if (file != null) {
                getPhotoListener.completeGetImage(file, upbitmap);
            }
        }
    }

    public void setGetPhotoListener(GetPhotoListener getPhotoListener) {
        this.getPhotoListener = getPhotoListener;
    }

    // 计算图片的缩放值
    public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {
            final int heightRatio = Math.round((float) height / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        }
        return inSampleSize;
    }

    // 根据路径获得图片并压缩，返回bitmap用于显示
    public static Bitmap getSmallBitmap(Bitmap bgimage) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;

        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, 480, 800);

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;

        // return BitmapFactory.decodeFile(filePath, options);
        return ZoomBitmap.zoomImage(bgimage, bgimage.getWidth()
                / options.inSampleSize, bgimage.getHeight() / options.inSampleSize);
    }

    // 把bitmap转换成String
    public static String bitmapToString(Bitmap bgimage) {
        Bitmap bm = getSmallBitmap(bgimage);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG, 40, baos);
        byte[] b = baos.toByteArray();
        return Base64.encodeToString(b, Base64.DEFAULT);
    }

}
